<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/1/15
 * Time: 23:05
 */
namespace app\admin\logic;


use  app\admin\logic\mqlogic\FanoutPublisher;
use  app\admin\logic\mqlogic\Consumer;
use app\common\model\zbtask\Import;
use app\common\utils\Utils;
use app\common\validate\zbtask\Import as ImportValidate ;
use think\Db;
use think\exception\ValidateException;
use think\Log;

class ImportMoney
{
    static $type = ['银行卡','支付宝','微信']; //账户类型
    static $money_type = [1 => '否' , 2 => '是']; //账户类型
    static $exchange = 'task_money';  //扇形交换机
    static $queue = 'task_money_queue';
    public function __construct($fieldArr = [])
    {

    }

   public function import($file = '', $task_id = 0) {
       if (!$task_id) {
           throw new ValidateException('任务ID未传递');
       }
       $fieldArr = [
           '真实姓名'=> 'real_name',
           '身份证号码'=> 'identity_card',
           '银行卡号' => 'bank_card',
           '手机号'   => 'mobile',
           '众包费' => 'money',
           '账户类型' => 'type',           //账户类别:0=银行卡,1=支付宝,2=微信
           '是否实发' => 'money_type',     //是否实发:0=实发,1=应发
           '所得项目' => 'item'
       ];
       try {
           $importService = new ImportService($fieldArr);
           $arr = $importService->import($file);
           $insertData = $this->processData($arr, $task_id);
           $importModel = new Import();
           //再导入之前删除之前的
           $importModel->saveAll($insertData);
       } catch (\Exception $e) {
           //导入文件失败， 把失败信息记录到文件中
           throw new ValidateException($e->getMessage());
       }

       return true;
   }

   protected function processData($arr, $task_id)
   {
       $returnArr = [];
       foreach ($arr as $k => &$v) {
           $v['mobile'] = (String)trim($v['mobile']);
           $v['real_name'] = (String)trim($v['real_name']);
           $v['identity_card'] = (String)trim($v['identity_card']);
           $v['bank_card'] = (String)trim($v['bank_card']);
           $v['item'] = (String)trim($v['item']);
           $v['type'] = self::getType(trim($v['type']), $k);
           $v['money_type'] = self::getMoneyType(trim($v['money_type']), $k);
           $v['money'] = sprintf("%.2f", trim($v['money']));
           $v['task_id'] = $task_id;
           if (!$v['identity_card'] && !$v['real_name']) {
               continue;
           }
           //已经导入的就不能再重新导入
           /*if (Import::get(['task_id' => $task_id, 'identity_card'=> $v['identity_card']])) {
               continue;
           }*/
           //初步过滤后，对数据信息进行认证
           try{
               $validate = validate('common/zbtask.import');
               $validate->goCheck(null, $v);
               $v['status'] = 1;
               $v['msg'] = '';
           } catch (ValidateException $e) {
                $msg = $e->getMessage();
                $v['status'] = 2;
                $v['msg'] = $msg;
           }d

           array_push($returnArr, $v);
       }

       return $returnArr;
   }

   protected function isInArr(&$arr, $new) {

        foreach ($arr as $k => &$v) {
            if ($v['identity_card'] == $new['identity_card']) {
                if ($v['money_type'] != $new ['money_type']) {
                    $v['status'] = 2;
                    $v['msg'] = $v['msg'] . '同一个表单中同一个人有两种实发和应发类型';
                }
                if ($v['type'] != $new ['type'] || $v['bank_card'] != $new['bank_card']) {
                    $v['status'] = 2;
                    $v['msg'] = $v['msg'] . '同一个表单中同一个人打款账户不一致';
                }

                //说明已经存在
                $v['money'] = Utils::processMoney($v['money'], $new['money'], '+');

                return true;
            }
        }

        return false;
   }

   /**
    * 银行类型
    * @param $val
    * @return int $type
    */
   protected static function getType($val, $i) {
        $type = false;
        foreach (self::$type as $k => $v) {
            if ($v == $val) {
                $type = $k;
            }
        }

        if ($type === false) {
            $i = $i + 2;
            throw new ValidateException('第' . $i .'行支付类型填写错误');
        }

        return $type;
   }

    /**
     * 银行类型
     * @param $val
     * @return int $type
     */
    protected static function getMoneyType($val, $i) {
        $type = false;
        foreach (self::$money_type as $k => $v) {
            if ($v == $val) {
                $type = $k;
            }
        }

        if ($type === false) {
            throw new ValidateException('第' . $i .'是否实发参数错误');
        }

        return $type;
    }

    /**
     * 队列 扇形队列
     */
    public function publisher($message) {
        $objMq = new FanoutPublisher(config('site.rabitmqconfig'));
        $objMq->setExchange(self::$exchange);

        $objMq->publish($message);
    }

    /**
     * 队列 扇形队列
     */
    public function consumer() {
        $config = config('site.rabitmqconfig');
        $objConsumer = new Consumer($config);
        $objConsumer->setQueue(self::$queue)->consume();
    }

    /**
     * 把文件写入数据库
     */
    public function fileLog($file, $task_id) {
        $data['file'] = $file;
        $data['task_id'] = $task_id;
        $where['file'] = $file;
        $where['task_id'] = $task_id;
        if (Db::name('zbtask_importlog')->where($where)->count() > 0) {
            return true;
        }
        return Db::name('zbtask_importlog')->insert($data);
    }

    public function fileRes($fileRes, $where) {
        return Db::name('zbtask_importlog')->where($where)->update($fileRes);
    }



}